package cn.edu.mju.auth.controller;


import cn.edu.mju.common.entity.result.R;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author cjy
 * @data 2023/6/12 8:37
 */

@RestController
@RefreshScope
public class CaptchaController {

    private final RedisTemplate<String,Object> redisTemplate;



    @Autowired
    public CaptchaController(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;

    }


    @GetMapping("/getCaptcha")
    public String createCaptcha(){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        // 图形验证码写出到指定文件
        lineCaptcha.write("F:/test/captcha.png");

        UUID uuid = UUID.randomUUID();

        //封装验证码
        HashMap<String,Object> r = new HashMap<>();
        r.put("img",lineCaptcha.getImageBase64());
        r.put("uuid",uuid.toString());

        //将验证码传入redis,2分钟后失效
        redisTemplate.opsForValue().set(uuid.toString(),lineCaptcha.getCode(),2, TimeUnit.MINUTES);
        return JSONObject.toJSONString(R.success(r));
    }





}
